<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" :request-api="getTableList" :init-param="initParam">
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button type="primary" :icon="CirclePlus" @click="openDrawer('新增')"> 新增 </el-button>
        <el-button type="primary" :icon="Download" plain @click="downloadFile">导出数据</el-button>
      </template>
      <template #endTime="scope">
        <span v-if="scope.row.endTime">{{ timeRender(scope) }}</span>
        <el-button v-else type="primary" link @click="onEndRushjob(scope.row)"> 结束突击 </el-button>
      </template>
      <template #workTime="scope">
        <el-button v-if="scope.row.workTime" type="primary" link @click="onCalcWorkTime(scope.row)">{{
          scope.row.workTime
        }}</el-button>
        <el-button v-if="!scope.row.workTime && scope.row.endTime" type="primary" link @click="onCalcWorkTime(scope.row)">
          重新计算
        </el-button>
        <span v-if="!scope.row.workTime && !scope.row.endTime">未结束突击</span>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button>
        <el-button type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)">编辑 </el-button>
      </template>
    </ProTable>
    <EditDrawer ref="drawerRef" />
    <InfoDialog ref="infoRef"></InfoDialog>
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive, computed, onMounted } from "vue";
import { ExportObj, RushJob } from "@/api/types/base";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import EditDrawer from "./editDrawer.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { CirclePlus, EditPen, View, Download } from "@element-plus/icons-vue";
import apiService from "@/api/services/apiService";
import { timeRender } from "@/hooks/useColumnRender";
import { useUserStore } from "@/stores/modules/user";
import InfoDialog from "@/layouts/components/Header/components/InfoDialog.vue";
import { ExportColType } from "@/enums/sysEnum";
import { ElMessageBox } from "element-plus";
import { useDownload } from "@/hooks/useDownload";
import { useDateFormat } from "@vueuse/core";
import { useDataStore } from "@/stores/modules/data";
import { userRender } from "@/hooks/useColumnRender";
import { RenderScope } from "@/components/ProTable/interface";
import { calculateOvertimeHours } from "@/utils";

const initVar = reactive({
  tbName: "rushJobs",
  tbCnName: "突击"
});

const defaultDate = ref<Date>(new Date());

// ProTable 实例
const proTable = ref<ProTableInstance>();
const userUser = useUserStore();
const dataStore = useDataStore();

const userList = computed(() => dataStore.userList);
onMounted(async () => {
  dataStore.findUserList();
});

const initParam = reactive({
  condition: {},
  options: { sort: { startTime: -1 } }
});

const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  if (newParams.condition && newParams.condition.startTime) {
    let curDate = new Date(newParams.condition.startTime);
    let [year, month] = [curDate.getFullYear(), curDate.getMonth()];
    let startDate = new Date(year, month, 1);
    let endDate = new Date(year, month + 1, 0, 23, 59, 59);
    newParams.condition.startTime = { $gte: startDate, $lte: endDate };
  }
  if (newParams.condition && newParams.condition.orgId) {
    newParams.condition.orgId = newParams.condition.orgId[newParams.condition.orgId.length - 1];
  }
  return apiService.findPage(initVar.tbName, newParams.condition, newParams.options);
};

const orgTree = computed(() => dataStore.orgTree);
onMounted(() => {
  dataStore.findOrgTree();
});

const changeDayRender: any = (scope: RenderScope<RushJob>) => {
  if (Number(scope.row["workTime"]) >= 6 && scope.row["isHoliday"] === "1") {
    return 0.5;
  } else {
    return "--";
  }
};

// 表格配置项
const columns = reactive<ColumnProps<RushJob>[]>([
  { type: "index", label: "序号", width: 85 },
  { prop: "userName", label: "姓名", width: 100, search: { el: "input", like: true, order: 3 } },
  { prop: "workNo", label: "工号", width: 100 },
  {
    prop: "orgId",
    label: "组织",
    width: 160,
    enum: orgTree,
    search: {
      el: "cascader",
      props: { filterable: true, showAllLevels: false, props: { value: "_id", label: "name" } },
      order: 2
    },
    fieldNames: { label: "name", value: "_id" }
  },
  { prop: "workNote", label: "突击内容", align: "left" },
  {
    prop: "startTime",
    label: "开始时间",
    width: 150,
    render: timeRender,
    search: { el: "date-picker", props: { type: "month" }, order: 1, defaultValue: defaultDate, label: "月份" }
  },
  {
    prop: "endTime",
    label: "结束时间",
    render: timeRender,
    width: 150
  },
  { prop: "workTime", label: "突击时间(小时)", width: 140 },
  {
    prop: "isHoliday",
    label: "节假日",
    width: 100,
    search: { el: "select", props: { filterable: true } },
    enum: () => apiService.findClassify("IS_NOT"),
    fieldNames: { label: "name", value: "value" }
  },
  { prop: "changeDay", label: "调休(天)", width: 100, render: changeDayRender },
  {
    prop: "charge_user",
    label: "审核人",
    width: 120,
    render: scope => userRender(scope, userList)
  },
  {
    prop: "state",
    label: "状态",
    width: 100,
    search: { el: "select", props: { filterable: true } },
    enum: () => apiService.findClassify("APPROVAL_STATE"),
    fieldNames: { label: "name", value: "value" }
  },
  { prop: "operation", label: "操作", align: "left", fixed: "right", width: 200 }
]);

const getExcelConfig = (): ExportObj => {
  let newParams = JSON.parse(JSON.stringify(proTable.value?.totalParam));
  if (newParams.condition.startTime) {
    let curDate = new Date(newParams.condition.startTime);
    let [year, month] = [curDate.getFullYear(), curDate.getMonth()];
    let startDate = new Date(year, month, 1);
    let endDate = new Date(year, month + 1, 0, 23, 59, 59);
    newParams.condition.startTime = { $gte: startDate, $lte: endDate };
  }
  if (newParams.condition.orgId && newParams.condition.orgId instanceof Array) {
    newParams.condition.orgId = newParams.condition.orgId[newParams.condition.orgId.length - 1];
  }
  return {
    params: newParams,
    tableName: initVar.tbName,
    keyPropName: "_id",
    enumTypes: ["APPROVAL_STATE", "IS_NOT"],
    tableConfigs: [
      { tableName: "orgs", fields: ["_id", "name"] },
      { tableName: "users", fields: ["_id", "userName"] }
    ],
    header: [
      { header: "序号", width: 6, ext: { prop: "index", type: ExportColType.INDEX } },
      {
        header: "姓名",
        width: 8,
        ext: { prop: "userName", type: ExportColType.DEFAULT }
      },
      { header: "工号", width: 10, ext: { prop: "workNo", type: ExportColType.DEFAULT } },
      { header: "组织", width: 15, ext: { prop: "orgId", type: ExportColType.TABLE, key: "orgs" } },
      { header: "突击内容", width: 50, ext: { prop: "workNote", func: "rushjobContent", type: ExportColType.CUSTOM } },
      {
        header: "开始时间",
        width: 16,
        ext: { prop: "startTime", type: ExportColType.DATE_TIME }
      },
      {
        header: "结束时间",
        width: 16,
        ext: { prop: "endTime", type: ExportColType.DATE_TIME }
      },
      {
        header: "突击时间(小时)",
        width: 8,
        ext: { prop: "workTime", type: ExportColType.DEFAULT }
      },
      {
        header: "节假日",
        width: 8,
        ext: { prop: "isHoliday", type: ExportColType.ENUM, key: "IS_NOT" }
      },
      {
        header: "审核人",
        width: 10,
        ext: { prop: "charge_user", type: ExportColType.TABLE, key: "users", label: "userName", value: "_id" }
      },
      { header: "状态", width: 10, ext: { prop: "state", type: ExportColType.ENUM, key: "APPROVAL_STATE" } }
    ]
  };
};

// 导出数据
const downloadFile = async () => {
  ElMessageBox.confirm("确认导出数据?", "温馨提示", { type: "warning" }).then(() =>
    useDownload(apiService.commonExport, `突击清单-${useDateFormat(new Date(), "YYYY-MM-DD").value}`, "", getExcelConfig(), false)
  );
};

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof EditDrawer> | null>(null);
const infoRef = ref<InstanceType<typeof InfoDialog> | null>(null);
const openDrawer = (title: string, row: Partial<RushJob> = {}) => {
  if (userUser.userInfo.workNo) {
    const params = {
      title,
      tbName: initVar.tbName,
      isView: title === "查看",
      row: row,
      api: title.indexOf("新增") !== -1 ? apiService.save : title === "编辑" ? apiService.updateById : undefined,
      getTableList: proTable.value?.getTableList
    };
    drawerRef.value?.acceptParams(params);
  } else {
    infoRef.value?.openDialog();
  }
};

const onEndRushjob = async row => {
  let curDate = new Date();
  let workTime = calculateOvertimeHours(row.startTime, row.endTime);
  row.endTime = curDate;
  row.workTime = workTime;
  useHandleData(apiService.updateById, initVar.tbName, { _id: row._id, endTime: curDate, workTime: workTime }, "结束突击").catch(
    () => {
      delete row.endTime;
      delete row.workTime;
    }
  );
};

const onCalcWorkTime = async row => {
  if (row.startTime && row.endTime) {
    let workTime = calculateOvertimeHours(row.startTime, row.endTime);
    await useHandleData(apiService.updateById, initVar.tbName, { _id: row._id, workTime: workTime }, "重新计算突击时间");
    row.workTime = workTime;
  }
};
</script>
